<?php

use think\Log;

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach ($iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var    数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}


// btc接口调用
function cbtapi()
{
    return config('cbtapi')['url'];
}

// 创建钱包（公钥私钥）
function wallet_api()
{

    $url = cbtapi() . 'CreateEtherWallet';
    $param['apikey'] = config('cbtapi')['apikey'];
    $data = http($url, $param);
    $data = json_decode($data, true);
    return $data['data'];
}

//查询指定地址币种余额
//addr 地址
//cointype 币种
function erc_yue($addr, $cointype)
{

    $cointype = strtoupper($cointype);
    $url = config('cbtapi')['url'];
    $param['apikey'] = config('cbtapi')['apikey'];
    if ($cointype == 'ETH') {
        $url = $url . 'getbalance';
        $param['address'] = $addr;
    } else {
        $url = $url . 'tokenbalance';
        $param['address'] = $addr;
        $param['contractaddress'] = config('site.erc_contract')[$cointype];

        $param['unit'] = config('site.erc_decimal')[$cointype];
    }

    $ret = \fast\Http::post($url, $param);

    $ret = json_decode($ret, true);
    if ($ret['code'] == 1 && isset($ret['data'])) {
        return ['zt' => 1, 'msg' => '', 'data' => $ret['data']];
    } else {
        Log::record('日志信息', $ret);
        return ['zt' => 0, 'msg' => '查询失败', 'data' => $ret, 'addr' => $addr];
    }
}

//查询交易是否到账 0查询失败，1交易成功，2交易失败，3交易中
function erc_daozhang($hash)
{
    $url = config('cbtapi')['url'];
    $param['apikey'] = config('cbtapi')['apikey'];
    $url = $url . 'gettransactionreceipt';
    $param['hash'] = $hash;
    $ret = \fast\Http::post($url, $param);
    $ret = json_decode($ret, true);
    if (isset($ret['code']) && $ret['code'] == 0) {
        return ['zt' => 3, 'msg' => '交易中', 'data' => $ret['data']];
    } elseif (isset($ret['code']) && $ret['code'] == 1 && isset($ret['data']['status']) && $ret['data']['status'] == '0x0') {
        return ['zt' => 2, 'msg' => '交易失败', 'data' => $ret['data']];
    } elseif (isset($ret['code']) && $ret['code'] == 1 && isset($ret['data']['status']) && $ret['data']['status'] == '0x1') {
        return ['zt' => 1, 'msg' => '交易成功', 'data' => $ret['data']];
    } else {
        return ['zt' => 0, 'msg' => '查询失败', 'data' => $ret, 'hash' => $hash];
    }
}

//执行ERC链上转账
function erc_zhuanzhang($cointype, $privatekey, $value, $to, $gasprice = "")
{
    $cointype = strtoupper($cointype);
    $url = config('cbtapi')['url'];
    $param['apikey'] = config('cbtapi')['apikey'];
    $param['privatekey'] = $privatekey;
    $param['value'] = $value;
    $param['to'] = $to;
    if ($gasprice) {
        $param['gasprice'] = $gasprice;
    }
    if ($cointype == 'ETH') {
        $url = $url . 'transferaccounts';
    } else {
        $url = $url . 'transfer';
        $param['contractaddress'] = config('site.erc_contract')[$cointype];
        $param['unit'] = config('site.erc_decimal')[$cointype];
    }

    // $ret = \fast\Http::post($url,$param);
    $ret = http($url, $param);
    $ret = json_decode($ret, true);

    // $ret['data']['hash'];
    if (isset($ret['code']) && $ret['code'] == 1 && $ret['data']) {
        return ['zt' => 1, 'msg' => '转账发送成功', 'data' => $ret['data']];
    } else {
        return ['zt' => 0, 'msg' => '转账发送失败', 'data' => $ret, 'param' => $param];
    }
}

//发送get/post请求
function http($url, $params = [], $method = 'GET', $timeout = 10)
{
    // return $url.'?'.http_build_query($params);

    if (!is_array($params) || empty($params)) {
        $params = [];
    }
    if (strtoupper($method) == 'POST') {
        $opts['http'] = [
            'method' => 'POST',
            'timeout' => $timeout,    //$timeout秒超时
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => http_build_query($params)
        ];
    } else {
        $opts['http'] = [
            'method' => 'GET',
            'timeout' => $timeout
        ];
        $url = $url . '?' . http_build_query($params);
    }
    $ret = @file_get_contents($url, false, stream_context_create($opts));
    return $ret;
}

// 功能：通过id获取用户信息
function userinfobyid($id)
{
    $userdata = db('user')->field(true)->where('id', $id)->find();
    if (!$userdata) return false;
    return $userdata;
}

// 功能：通过username获取用户信息
function userinfobyusername($username)
{
    $userdata = db('user')->field(true)->where('username', $username)->find();
    if (!$userdata) return false;
    return $userdata;
}

// 功能：通过username获取用户信息
function userinfotjm($tjm)
{
    $userdata = db('user')->field(true)->where('tjm', $tjm)->find();
    if (!$userdata) return false;
    return $userdata;
}

/*
 * 加密解密类
 * 该算法仅支持加密数字。比较适用于数据库中id字段的加密解密，以及根据数字显示url的加密。
 * @加密原则 标记长度 + 补位 + 数字替换
 * @加密步骤：
 * 将a-z,A-Z,0-9 62个字符打乱，取前M(数字最大的位数)位作为 标记长度字符串，取第M+1 到第M+10位为数字替换字符串，剩余的为补位字符串
 * 1.计算数字长度n,取乱码的第n位作为标记长度。
 * 2.计算补位的长度，加密串的长度N -1 - n 为补位的长度。根据指定的算法得到补位字符串。
 * 3.根据数字替换字符串替换数字，得到数字加密字符串。
 * 标记长度字符 + 补位字符串 + 数字加密字符串 = 加密串
 */
function authcodenum($str, $mode = "decode", $length = "9")
{  //KM++纯数字的加密解密
    $strbase = "T7aPdkK3ziZe6OfStvru9oEcGx28sgNWQY4FlVqH1LyDhCUAjX0nJBmpbI5MRw";
    $key = 2543.5415412812;
    $length = $length;
    $codelen = substr($strbase, 0, $length);
    $codenums = substr($strbase, $length, 10);
    $codeext = substr($strbase, $length + 10);
    if ($mode == "decode") {
        $code = $str;
        $begin = substr($code, 0, 1);
        $rtn = '';
        $len = strpos($codelen, $begin);
        if ($len !== false) {
            $len++;
            $arrnums = str_split(substr($code, -$len));
            foreach ($arrnums as $v) {
                $rtn .= strpos($codenums, $v);
            }
        }
        return $rtn;
    } else {
        $nums = $str;
        $rtn = "";
        $numslen = strlen($nums);
        //密文第一位标记数字的长度
        $begin = substr($codelen, $numslen - 1, 1);
        //密文的扩展位
        $extlen = $length - $numslen - 1;
        $temp = str_replace('.', '', $nums / $key);
        $temp = substr($temp, -$extlen);
        $arrextTemp = str_split($codeext);
        $arrext = str_split($temp);
        foreach ($arrext as $v) {
            $rtn .= $arrextTemp[$v];
        }
        $arrnumsTemp = str_split($codenums);
        $arrnums = str_split($nums);
        foreach ($arrnums as $v) {
            $rtn .= $arrnumsTemp[$v];
        }
        return $begin . $rtn;
    }
}

/**
 * 保留几位小数，向下取整
 *$num 要处理的浮点数
 *$digits 要保留的小数位数
 * 实现思路：先乘以10的小数位数次方，用floor向下取整，再除以除数得到舍去后面位数的结果
 * 最后再用sprintf配合位数再取一次值（此处是为了解决有些数字属，最后一位为零时不显示问题）
 */
function floorFloat($num, $digits)
{
    $num = floatval($num);
    $multiple = pow(10, $digits);
    $tempNum = floor($num * $multiple);
    return sprintf('%.' . $digits . 'f', $tempNum / $multiple);
}


// 手续费查询
// 转账速度 $cost 1-慢 ,2-平均值,3-快
function apigasPrice($cost = 1)
{
    $url = cbtapi() . 'apigasPrice';
    $param['apikey'] = config('cbtapi')['apikey'];
    //发送
    $result = http($url, $param);
    $rsp = json_decode($result, true);

    $gwei = bcdiv($rsp['data'], bcpow(10, 9), 6);
    if ($cost == 2) {
        $gwei += 4;
    } elseif ($cost == 3) {
        $gwei += 8;
    }
    $ether = bcdiv($gwei * 60000, bcpow(10, 9), 6);

    return $ether;
}

// 订单生成
function orderSn()
{
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    return $yCode[intval(date('Y')) - 2011] . date('d') . substr(time(), -5) . sprintf('%02d', rand(0, 99));
}





function zhitui($user,$money)
{
    $zhitui = config('site.zhitui');
    $user_tid = userinfobyid($user['tid']);
    $moeny = $money * $zhitui / 100;
    if($user_tid){
        $qian_log = [
            'uid' => $user_tid['id'],
            'uname' => $user_tid['username'],
            'bizhong' => 'usdt',
            'money' =>  $moeny,
            'before' => $user_tid['usdt'],
            'after' => $user_tid['usdt'] + $moeny,
            'type' => 8,
            'zt' => 1,
            'memo' => $user['username'].' 的直推奖',
          ];
        $user_t = [
        'id' => $user_tid['id'],
        'usdt' => $user_tid['usdt'] + $moeny
        ];

        $data['user'] =  $user_t;
        $data['qian_log'] =  $qian_log;
        return $data;    
    }else{
        return false;
    }


}


